<template>
  <div>
    <div class="search">
      <el-input placeholder="请输入订单编号查询" style="width: 200px" v-model="number"></el-input>
      <el-input placeholder="请输入用户编号查询" style="width: 200px; margin-left: 10px" v-model="userId"></el-input>
      <el-input placeholder="请输入商品名称查询" style="width: 200px; margin-left: 10px" v-model="productName"></el-input>
<!--      <el-select v-model="status" placeholder="请选择支付状态" style="margin-left: 10px">-->
<!--        <el-option-->
<!--            v-for="item in statusOptions"-->
<!--            :key="item.value"-->
<!--            :label="item.label"-->
<!--            :value="item.value">-->
<!--        </el-option>-->
<!--      </el-select>-->
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

<!--    <div class="operation">-->
<!--      <el-button type="primary" plain @click="handleAdd">新增</el-button>-->
<!--&lt;!&ndash;      <el-button type="danger" plain @click="delBatch">批量删除</el-button>&ndash;&gt;-->
<!--    </div>-->


    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待支付" name="awaitingPayment"></el-tab-pane>
      <el-tab-pane label="支付成功" name="paymentSuccess"></el-tab-pane>
      <el-tab-pane label="已完成" name="completed"></el-tab-pane>
      <el-tab-pane label="纠纷中" name="inDispute"></el-tab-pane>
      <el-tab-pane label="处理完成" name="handled"></el-tab-pane>
      <el-tab-pane label="评价审核" name="reviewing"></el-tab-pane>
      <el-tab-pane label="已评价" name="reviewed"></el-tab-pane>
      <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
    </el-tabs>

    <div class="table">
      <el-table :data="tableData" strip @selection-change="handleSelectionChange">
        <el-table-column prop="number" label="订单编号" width="200"></el-table-column>
        <el-table-column prop="userId" label="购买用户编号"></el-table-column>
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column prop="amount" label="总金额"></el-table-column>
        <el-table-column prop="status" label="订单状态" :formatter="formatState"></el-table-column>
        <el-table-column prop="creationTime" label="创建时间"></el-table-column>
        <el-table-column prop="paymentTime" label="支付完成时间"></el-table-column>
        <el-table-column prop="comnpletionTime" label="订单完成时间"></el-table-column>
        <el-table-column prop="description" label="订单备注"></el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">查看详细</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>


    <el-dialog title="订单详情" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="form" label-width="100px" style="padding-right: 50px" ref="formRef">
        <el-form-item label="订单编号" prop="number">
          <el-input v-model="form.number" placeholder="订单编号" readonly></el-input>
        </el-form-item>
        <el-form-item label="购买用户编号" prop="userId">
          <el-input v-model="form.userId" placeholder="购买用户编号" readonly></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="商品名称" readonly></el-input>
        </el-form-item>
        <el-form-item label="总金额" prop="amount">
          <el-input v-model="form.amount" placeholder="总金额" readonly></el-input>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-input v-model="form.status" placeholder="订单状态" readonly></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="creationTime">
          <el-input v-model="form.creationTime" placeholder="创建时间" readonly></el-input>
        </el-form-item>
        <el-form-item label="支付完成时间" prop="paymentTime">
          <el-input v-model="form.paymentTime" placeholder="支付完成时间" readonly></el-input>
        </el-form-item>
        <el-form-item label="订单完成时间" prop="comnpletionTime">
          <el-input v-model="form.comnpletionTime" placeholder="订单完成时间" readonly></el-input>
        </el-form-item>
        <el-form-item label="订单备注" prop="description">
          <el-input v-model="form.description" placeholder="订单备注" type="textarea" :rows="3" readonly></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">关 闭</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
export default {
  name: "Order",
  data() {
    return {
      tableData: [],  // 所有的数据
      activeTab: 'all',
      productsData: [], // 商品数据
      specificationsData: [], // 所有规格数据
      filteredSpecifications: [], // 过滤后的规格数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      productName: null,
      number: null,
      userId: null,
      status: null,
      fromVisible: false,
      form: {},
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'},
        ]
      },
      ids: []
    }
  },
  created() {
    this.activeTab = 'all'; // 设置默认激活的标签页为 '全部'
    this.load(1)
    this.loadProducts();//获取商品信息
    this.loadSpcifications();//获取商品规格信息
  },
  methods: {

    handleTabClick(tab) {
      console.log('handleTabClick 方法被调用了');
      switch(tab.name) {
        case 'awaitingPayment':
          this.currentState = 0; // 待支付
          break;
        case 'paymentSuccess':
          this.currentState = 1; // 支付成功
          break;
        case 'completed':
          this.currentState = 2; // 已完成
          break;
        case 'inDispute':
          this.currentState = 3; // 纠纷中
          break;
        case 'handled':
          this.currentState = 4; // 处理完成
          break;
        case 'reviewing':
          this.currentState = 5; // 评价审核
          break;
        case 'reviewed':
          this.currentState = 6; // 已评价
          break;
        case 'cancelled':
          this.currentState = 7; // 已取消
          break;
        case 'all':
          this.currentState = null; // 全部
          break;
        default:
          this.currentState = null;
      }

      this.load(1); // 重新加载表格数据
    },

    handleAdd() {   // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.fromVisible = true   // 打开弹窗
    },
    loadProducts() { //获取商品数据
      if (this.user.admin === undefined){
        this.$request.get('/employee/api/product/pages').then(res => {
          this.productsData = res.records;
          console.log( this.productsData)
          this.productsData = this.uniqueProducts(this.productsData);
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }else{
        this.$request.get('/admin/api/product/pages').then(res => {
          this.productsData = res.records;
          console.log( this.productsData)
          this.productsData = this.uniqueProducts(this.productsData);
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }
    },
    loadSpcifications() { //获取商品数据
      if (this.user.admin === undefined){
        this.$request.get('/employee/api/specifications/pages').then(res => {
          this.specificationsData = res.records;
          console.log(this.specificationsData)
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }else {
        this.$request.get('/admin/api/specifications/pages').then(res => {
          this.specificationsData = res.records;
          console.log(this.specificationsData)
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }
    },

    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      this.fromVisible = true   // 打开弹窗
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新

      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.id ? '/user/api/order/create' : '/user/api/admin/add',
            method: this.form.id ? 'POST' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === 0) {  // 表示成功保存
              this.$message.success('保存成功')
              this.load(1)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    del(id) {   // 单个删除
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/user/api/order/delete/' + id).then(res => {
          if (res.code === 0) {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },

    formatState(row, column, cellValue) {
      // 根据state的值返回相应的文本
      switch (cellValue) {
        case 0:
          return '待支付'; // awaitingPayment
        case 1:
          return '支付成功'; // paymentSuccess
        case 2:
          return '已完成'; // completed
        case 3:
          return '纠纷中'; // inDispute
        case 4:
          return '处理完成'; // handled
        case 5:
          return '评价审核'; // reviewing
        case 6:
          return '已评价'; // reviewed
        case 7:
          return '已取消'; // cancelled
        default:
          return '未知状态';
      }
    },


    // handlePaynpment(row) {
    //   // 假设 row 对象包含订单的所有信息，包括订单ID
    //   // 这里应该是调用支付逻辑的方法
    //   // 由于您已经提供了 handlePayment 方法，我们可以假设这是处理支付的方法
    //   this.handlePayment(row);
    // },
    // handlePayment: async function (row) {
    //   try {
    //     // 等待获取支付URL的响应
    //     const response = await this.$request.get('/admin/api/alipay/pay/' + row.id);
    //     // 假设支付URL在响应数据的data字段中
    //     const payUrl = response.data;
    //     // 使用获取到的支付URL打开新窗口
    //     window.open(payUrl, '_blank');
    //   } catch (error) {
    //     console.error('支付请求失败:', error);
    //     // 在这里处理错误，例如显示错误消息给用户
    //     this.$message.error('支付请求失败，请稍后再试。');
    //   }
    // },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)
    },
    delBatch() {   // 批量删除
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/user/api/order/delete/batch', {data: this.ids}).then(res => {
          if (res.code === 0) {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },

    load(pageNum) {  // 分页查询

      if (pageNum) this.pageNum = pageNum
      if (this.user.admin === undefined)
        this.$request.get('/employee/api/order/pages', {
          params: {
            current: this.pageNum,
            size: this.pageSize,
            number: this.number,
            userId: this.userId,
            productName: this.productName,
            // 添加状态参数，如果currentState为null，则不传递该参数，即查询所有状态
            status: this.currentState !== null ? this.currentState : undefined,

          }
        }).then(res => {

          this.tableData = res.records
          this.total = res.total
        })
      else
        this.$request.get('/admin/api/order/pages', {
          params: {
            current: this.pageNum,
            size: this.pageSize,
            number: this.number,
            userId: this.userId,
            productName: this.productName,
            // 添加状态参数，如果currentState为null，则不传递该参数，即查询所有状态
            status: this.currentState !== null ? this.currentState : undefined,
          }
        }).then(res => {
          this.tableData = res.records
          this.total = res.total
        })
      },
    reset() {
      this.number = null
      this.userId = null
      this.productName = null
      this.status = null
      this.load(1)
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把头像属性换成上传的图片的链接
      this.form.avatar = response.data
    },
  }
}
</script>

<style scoped>

</style>